import { Repository } from 'typeorm';
import { AppDataSource } from '../config/database';
import { User } from '../models/User';

export class UserService {
  private userRepository: Repository<User>;

  constructor() {
    this.userRepository = AppDataSource.getRepository(User);
  }

  async create(userData: Partial<User>): Promise<User> {
    const user = this.userRepository.create(userData);
    return await this.userRepository.save(user);
  }

  async createUser(userData: Partial<User>): Promise<User> {
    return this.create(userData);
  }

  async findById(id: number): Promise<User | null> {
    return await this.userRepository.findOne({ where: { id } });
  }

  async findUserById(id: number): Promise<User | null> {
    return this.findById(id);
  }

  async findByEmail(email: string): Promise<User | null> {
    return await this.userRepository.findOne({ 
      where: { email },
      select: ['id', 'email', 'username', 'password', 'role', 'isActive']
    });
  }

  async findUserByEmail(email: string): Promise<User | null> {
    return this.findByEmail(email);
  }

  async findAll(page = 1, limit = 10): Promise<{ users: User[]; total: number }> {
    const [users, total] = await this.userRepository.findAndCount({
      skip: (page - 1) * limit,
      take: limit,
      order: { createdAt: 'DESC' },
    });

    return { users, total };
  }

  async findAllUsers(page = 1, limit = 10): Promise<{ users: User[]; total: number }> {
    return this.findAll(page, limit);
  }

  async update(id: number, userData: Partial<User>): Promise<User | null> {
    await this.userRepository.update(id, userData);
    return await this.findById(id);
  }

  async updateUser(id: number, userData: Partial<User>): Promise<User | null> {
    return this.update(id, userData);
  }

  async delete(id: number): Promise<boolean> {
    const result = await this.userRepository.delete(id);
    return result.affected !== 0;
  }

  async deleteUser(id: number): Promise<boolean> {
    return this.delete(id);
  }

  async checkEmailExists(email: string): Promise<boolean> {
    const count = await this.userRepository.count({ where: { email } });
    return count > 0;
  }
}